package mspdt.pocket.wallet;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBAdapter extends SQLiteOpenHelper{
	 
    //The Android's default system path of your application database.
    private static String DB_PATH = "/data/data/mspdt.pocket.wallet/databases/";
    private static String DB_NAME = "mobilewallet.db";
    private static String TABLE_NAME_USER = "user";
    private static String TABLE_NAME_ACCOUNT = "account";
    private static String TABLE_NAME_INCOME_GROUP = "income_group";
    private static String TABLE_NAME_INCOME_CATEGORY = "income_category";
    private static String TABLE_NAME_EXPENSE_GROUP = "expense_group";
    private static String TABLE_NAME_EXPENSE_CATEGORY = "expense_category";
    private static String TABLE_NAME_JOURNAL = "journal";
    
    private static String USER_ID = "id";
    private static String USER_PASSWORD = "password";
    private static String USER_LOGIN = "lastlogin";
    private static String USER_FIRST = "firstlogin";
    private static String USER_EXPIRE = "expire";
    
    private static String ACCOUNT_ID = "id";
    private static String ACCOUNT_NAME = "name";
    private static String ACCOUNT_DESC = "desc";
    private static String ACCOUNT_START_BALANCE = "start_balance";
    private static String ACCOUNT_FINAL_BALANCE = "final_balance";
    
    private static String INCOME_GROUP_ID = "id";
    private static String INCOME_GROUP_NAME = "name";
    private static String INCOME_GROUP_DESC = "desc";
    
    private static String INCOME_CATEGORY_ID = "id";
    private static String INCOME_CATEGORY_NAME = "name";
    private static String INCOME_CATEGORY_DESC = "desc";
    private static String INCOME_CATEGORY_GROUP_ID = "income_group_id";
    
    private static String EXPENSE_GROUP_ID = "id";
    private static String EXPENSE_GROUP_NAME = "name";
    private static String EXPENSE_GROUP_DESC = "desc";
    
    private static String EXPENSE_CATEGORY_ID = "id";
    private static String EXPENSE_CATEGORY_NAME = "name";
    private static String EXPENSE_CATEGORY_DESC = "desc";
    private static String EXPENSE_CATEGORY_GROUP_ID = "expense_group_id";
    
    private static String JOURNAL_ID = "id";
    private static String JOURNAL_DOCDATE = "docdate";
    private static String JOURNAL_DESC = "desc";
    private static String JOURNAL_AMOUNT = "amount";
    private static String JOURNAL_CATEGORY_ID = "category_id";
    private static String JOURNAL_IMAGE = "image";
    private static String JOURNAL_PRG = "prg";
    private static String JOURNAL_DEB_ACC = "deb_acc";
    private static String JOURNAL_KRE_ACC = "kre_acc";
    private static String JOURNAL_ACCOUNT_ID = "account_id";
    
    private static String CATEGORY = "category";
    private static String NAME = "name";
    private static String INGREDIENTS = "ingredient";
    
    
    private SQLiteDatabase myDataBase; 
    private final Context myContext;
    
 
    /**
     * Constructor
     * Takes and keeps a reference of the passed context in order to access to the application assets and resources.
     * @param context
     */

    
   
   
    public DBAdapter(Context context) {
 
    	super(context, DB_NAME, null, 1);
        this.myContext = context;
        try {
			createDataBase();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }	
 
  /**
     * Creates a empty database on the system and rewrites it with your own database.
     * */
    public void createDataBase() throws IOException{
 
    	boolean dbExist = checkDataBase();
 
    	if(dbExist){
    		//do nothing - database already exist
    	}else{
 
    		//By calling this method and empty database will be created into the default system path
               //of your application so we are gonna be able to overwrite that database with our database.
        	this.getReadableDatabase();
 
        	try {
 
    			copyDataBase();
    		} catch (IOException e) {
 
        		throw new Error("Error copying database");
 
        	}
        	this.close();
    	}
 
    }
 
    /**
     * Check if the database already exist to avoid re-copying the file each time you open the application.
     * @return true if it exists, false if it doesn't
     */
    private boolean checkDataBase(){
 
    	SQLiteDatabase checkDB = null;
 
    	try{
    		String myPath = DB_PATH + DB_NAME;
    		checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
 
    	}catch(SQLiteException e){
 
    		//database does't exist yet.
 
    	}
 
    	if(checkDB != null){
 
    		checkDB.close();
 
    	}
 
    	return checkDB != null ? true : false;
    }
 
    /**
     * Copies your database from your local assets-folder to the just created empty database in the
     * system folder, from where it can be accessed and handled.
     * This is done by transfering bytestream.
     * */
    private void copyDataBase() throws IOException{
 
    	//Open your local db as the input stream
    	InputStream myInput = myContext.getAssets().open(DB_NAME);
 
    	// Path to the just created empty db
    	String outFileName = DB_PATH + DB_NAME;
 
    	//Open the empty db as the output stream
    	OutputStream myOutput = new FileOutputStream(outFileName);
 
    	//transfer bytes from the inputfile to the outputfile
    	byte[] buffer = new byte[1024];
    	int length;
    	while ((length = myInput.read(buffer))>0){
    		myOutput.write(buffer, 0, length);
    	}
 
    	//Close the streams
    	myOutput.flush();
    	myOutput.close();
    	myInput.close();
    	openDataBase();
    	
    }
 
    public void openDataBase() throws SQLException{
 
    	//Open the database
        String myPath = DB_PATH + DB_NAME;
    	myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
    	
 
    }
 
    @Override
	public synchronized void close() {
 
    	    if(myDataBase != null)
    		    myDataBase.close();
 
    	    super.close();
 
	}
 
	@Override
	public void onCreate(SQLiteDatabase db) {
 
	}
 
	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
 
	}
	
	public String getPassword()
	{
		String password = null;
		Cursor cursor = this.myDataBase.query(TABLE_NAME_USER, new String[] {this.USER_PASSWORD}, null, null, null, null, null);
		if(cursor.moveToFirst())
		{
			password= cursor.getString(0);
		}

			if(cursor != null || !cursor.isClosed())
				cursor.close();
			return password;
		
	}
	public void setPassword(String password, boolean isHaveOld)
	{
		if(isHaveOld)
			myDataBase.execSQL("UPDATE "+TABLE_NAME_USER+" SET "+USER_PASSWORD+"='"+password+"'");
		else
			myDataBase.execSQL("INSERT INTO " + TABLE_NAME_USER + "("+USER_PASSWORD+") values ('"+password+"')");
	}
	public ArrayList<String> getAccounts()
	{
		ArrayList<String> accounts = new ArrayList<String>();
		Cursor cursor = this.myDataBase.query(TABLE_NAME_ACCOUNT, new String[] {this.ACCOUNT_NAME}, null, null, null, null, null);
		if(cursor.moveToFirst())
			do
			{
				accounts.add(cursor.getString(0));
			}
			while(cursor.moveToNext());
		if(cursor != null || !cursor.isClosed())
			cursor.close();
		return accounts;
	}
	public ArrayList<String> getAmounts()
	{
		ArrayList<String> amounts = new ArrayList<String>();
		Cursor cursor = this.myDataBase.query(TABLE_NAME_ACCOUNT, new String[] {this.ACCOUNT_FINAL_BALANCE}, null, null, null, null, null);
		if(cursor.moveToFirst())
			do
			{
				amounts.add(cursor.getString(0));
			}
			while(cursor.moveToNext());
		if(cursor != null || !cursor.isClosed())
			cursor.close();
		return amounts;
	}
	public ArrayList<Integer> getAccountIds()
	{
		ArrayList<Integer> ids = new ArrayList<Integer>();
		Cursor cursor = this.myDataBase.query(TABLE_NAME_ACCOUNT, new String[] {this.ACCOUNT_ID}, null, null, null, null, null);
		if(cursor.moveToFirst())
			do
			{
				ids.add(cursor.getInt(0));
			}
			while(cursor.moveToNext());
		if(cursor != null || !cursor.isClosed())
			cursor.close();
		return ids;
	}
	public ArrayList<String> getAccountCategories(int account_id)
	{
		ArrayList<String> account_categories = new ArrayList<String>();
		Cursor cursor = this.myDataBase.query(TABLE_NAME_JOURNAL, new String[] {this.JOURNAL_ACCOUNT_ID, this.JOURNAL_CATEGORY_ID, this.JOURNAL_PRG}, null, null, null, null, null);
		if(cursor.moveToFirst())
			do
			{
				if(account_id==cursor.getInt(0))
				{
					if(cursor.getString(2).equals("exp"))
						account_categories.add(getExpenseCategory(cursor.getInt(1)));
					else if(cursor.getString(2).equals("inc"))
						account_categories.add(getIncomeCategory(cursor.getInt(1)));
					else
						account_categories.add(myContext.getResources().getString(R.string.transfer));
				}
			}
			while(cursor.moveToNext());
		if(cursor != null || !cursor.isClosed())
			cursor.close();
		return account_categories;
	}
	public Cursor getData(String[] datas)
	{
		Cursor cursor = this.myDataBase.query(TABLE_NAME_JOURNAL, datas, null, null, null, null, null, null);
		return cursor;
	}
	public ArrayList<String> getAccountAmounts(int account_id)
	{
		ArrayList<String> account_amounts = new ArrayList<String>();
		Cursor cursor = this.myDataBase.query(TABLE_NAME_JOURNAL, new String[] {this.JOURNAL_ACCOUNT_ID, this.JOURNAL_AMOUNT}, null, null, null, null, null);
		if(cursor.moveToFirst())
			do
			{
				if(account_id==cursor.getInt(0))
				{
					account_amounts.add(cursor.getString(1));
				}
			}
			while(cursor.moveToNext());
		if(cursor != null || !cursor.isClosed())
			cursor.close();
		return account_amounts;
	}
	private int getIncomeGroupId(int cat_id)
	{
		int id = 0;
		Cursor cursor = this.myDataBase.query(TABLE_NAME_INCOME_CATEGORY, new String[] {this.INCOME_CATEGORY_ID, this.INCOME_CATEGORY_GROUP_ID}, null, null, null, null, null);
		if(cursor.moveToFirst())
		{
			do
			{
				if(cat_id == cursor.getInt(0))
				{
					id = cursor.getInt(1);
					cursor.close();
					return id;
				}
			}
			while(cursor.moveToNext());
		}
		if(cursor != null || !cursor.isClosed())
			cursor.close();
		return id;
	}
	private int getExpenseGroupId(int cat_id)
	{
		int id = 0;
		Cursor cursor = this.myDataBase.query(TABLE_NAME_EXPENSE_CATEGORY, new String[] {this.EXPENSE_CATEGORY_ID, this.EXPENSE_CATEGORY_GROUP_ID}, null, null, null, null, null);
		if(cursor.moveToFirst())
		{
			do
			{
				if(cat_id == cursor.getInt(0))
				{
					id = cursor.getInt(1);
					cursor.close();
					return id;
				}
			}
			while(cursor.moveToNext());
		}
		if(cursor != null || !cursor.isClosed())
			cursor.close();
		return id;
	}
	public ArrayList<Integer> getGroups(int account_id)
	{
		ArrayList<Integer> groups = new ArrayList<Integer>();
		Cursor cursor = this.myDataBase.query(TABLE_NAME_JOURNAL, new String[] {this.JOURNAL_ACCOUNT_ID, this.JOURNAL_PRG, this.JOURNAL_CATEGORY_ID}, null, null, null, null, null);
		if(cursor.moveToFirst())
			do
			{
				if(account_id==cursor.getInt(0))
				{
					if(cursor.getString(1).equals("exp"))
						groups.add(getExpenseGroupId(cursor.getInt(2)));
					else if(cursor.getString(1).equals("inc"))
						groups.add(getIncomeGroupId(cursor.getInt(2)));
					else
						groups.add(-1);
				}
			}
			while(cursor.moveToNext());
		if(cursor != null || !cursor.isClosed())
			cursor.close();
		return groups;
	}
	public ArrayList<String> getAccountDescriptions(int account_id)
	{
		ArrayList<String> account_descriptions = new ArrayList<String>();
		Cursor cursor = this.myDataBase.query(TABLE_NAME_JOURNAL, new String[] {this.JOURNAL_ACCOUNT_ID, this.JOURNAL_DESC}, null, null, null, null, null);
		if(cursor.moveToFirst())
			do
			{
				if(account_id==cursor.getInt(0))
				{
					account_descriptions.add(cursor.getString(1));
				}
			}
			while(cursor.moveToNext());
		if(cursor != null || !cursor.isClosed())
			cursor.close();
		return account_descriptions;
	}
	public ArrayList<String> getAccountDates(int account_id)
	{
		ArrayList<String> account_dates = new ArrayList<String>();
		Cursor cursor = this.myDataBase.query(TABLE_NAME_JOURNAL, new String[] {this.JOURNAL_ACCOUNT_ID, this.JOURNAL_DOCDATE}, null, null, null, null, null);
		if(cursor.moveToFirst())
			do
			{
				if(account_id==cursor.getInt(0))
				{
					account_dates.add(cursor.getString(1));
				}
			}
			while(cursor.moveToNext());
		if(cursor != null || !cursor.isClosed())
			cursor.close();
		return account_dates;
	}
	public ArrayList<String> getAccountPRG(int account_id)
	{
		ArrayList<String> account_prg = new ArrayList<String>();
		Cursor cursor = this.myDataBase.query(TABLE_NAME_JOURNAL, new String[] {this.JOURNAL_ACCOUNT_ID, this.JOURNAL_PRG}, null, null, null, null, null);
		if(cursor.moveToFirst())
			do
			{
				if(account_id==cursor.getInt(0))
				{
					account_prg.add(cursor.getString(1));
				}
			}
			while(cursor.moveToNext());
		if(cursor != null || !cursor.isClosed())
			cursor.close();
		return account_prg;
	}
	public ArrayList<String> getAccountDEB(int account_id)
	{
		ArrayList<String> account_deb = new ArrayList<String>();
		Cursor cursor = this.myDataBase.query(TABLE_NAME_JOURNAL, new String[] {this.JOURNAL_ACCOUNT_ID, this.JOURNAL_DEB_ACC}, null, null, null, null, null);
		if(cursor.moveToFirst())
			do
			{
				if(account_id==cursor.getInt(0))
				{
					account_deb.add(cursor.getString(1));
				}
			}
			while(cursor.moveToNext());
		if(cursor != null || !cursor.isClosed())
			cursor.close();
		return account_deb;
	}
	public ArrayList<String> getAccountKRE(int account_id)
	{
		ArrayList<String> account_kre = new ArrayList<String>();
		Cursor cursor = this.myDataBase.query(TABLE_NAME_JOURNAL, new String[] {this.JOURNAL_ACCOUNT_ID, this.JOURNAL_KRE_ACC}, null, null, null, null, null);
		if(cursor.moveToFirst())
			do
			{
				if(account_id==cursor.getInt(0))
				{
					account_kre.add(cursor.getString(1));
				}
			}
			while(cursor.moveToNext());
		if(cursor != null || !cursor.isClosed())
			cursor.close();
		return account_kre;
	}
	public void addToJournal(String date, String desc, String amount, int category_id, String image, String prg, String deb_acc, String kre_acc, int account_id)
	{
		myDataBase.execSQL("INSERT INTO "+TABLE_NAME_JOURNAL+" ("+JOURNAL_DOCDATE+", "+JOURNAL_DESC+", "+JOURNAL_AMOUNT+", "+JOURNAL_CATEGORY_ID+", " +
				JOURNAL_IMAGE+", "+JOURNAL_PRG+", "+JOURNAL_DEB_ACC+", "+JOURNAL_KRE_ACC+", "+JOURNAL_ACCOUNT_ID+") VALUES ('"+date+"', '"+desc+"', '" +
						amount+"', "+category_id+", '"+image+"', '"+prg+"', '"+deb_acc+"', '"+kre_acc+"', "+account_id+")");
	}
	public String getIncomeGroup(int id)
	{
		String group = null;
		Cursor cursor = this.myDataBase.query(TABLE_NAME_INCOME_GROUP, new String[] {this.INCOME_GROUP_ID, this.INCOME_GROUP_NAME}, null, null, null, null, null);
		if(cursor.moveToFirst())
			do
			{
				if(id==cursor.getInt(0))
				{
					group=cursor.getString(1);
					cursor.close();
					return group;
				}
					
			}
			while(cursor.moveToNext());
		if(cursor != null || !cursor.isClosed())
			cursor.close();
		return group;
	}
	public String getExpenseGroup(int id)
	{
		String group = null;
		Cursor cursor = this.myDataBase.query(TABLE_NAME_EXPENSE_GROUP, new String[] {this.EXPENSE_GROUP_ID, this.EXPENSE_GROUP_NAME}, null, null, null, null, null);
		if(cursor.moveToFirst())
			do
			{
				if(id==cursor.getInt(0))
				{
					group=cursor.getString(1);
					cursor.close();
					return group;
				}
					
			}
			while(cursor.moveToNext());
		if(cursor != null || !cursor.isClosed())
			cursor.close();
		return group;
	}
	public String getIncomeCategory(int id)
	{
		String category = null;
		Cursor cursor = this.myDataBase.query(TABLE_NAME_INCOME_CATEGORY, new String[] {this.INCOME_CATEGORY_ID, this.INCOME_CATEGORY_NAME}, null, null, null, null, null);
		if(cursor.moveToFirst())
			do
			{
				if(id==cursor.getInt(0))
				{
					category=cursor.getString(1);
					cursor.close();
					return category;
				}
					
			}
			while(cursor.moveToNext());
		if(cursor != null || !cursor.isClosed())
			cursor.close();
		return category;
	}
	public String getExpenseCategory(int id)
	{
		String category = null;
		Cursor cursor = this.myDataBase.query(TABLE_NAME_EXPENSE_CATEGORY, new String[] {this.EXPENSE_CATEGORY_ID, this.EXPENSE_CATEGORY_NAME}, null, null, null, null, null);
		if(cursor.moveToFirst())
			do
			{
				if(id==cursor.getInt(0))
				{
					category=cursor.getString(1);
					cursor.close();
					return category;
				}
					
			}
			while(cursor.moveToNext());
		if(cursor != null || !cursor.isClosed())
			cursor.close();
		return category;
	}
}